<template>
	<view class="classification-container">
		<!-- 自定义导航栏 - 小程序适配版本 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content"
				:style="{ height: navBarHeight + 'px', paddingRight: menuButtonInfo.width + menuButtonInfo.right - windowWidth + 10 + 'px' }">
				<view class="scan-btn" @click="scanCode">
					<u-icon name="scan" size="20" color="#fff"></u-icon>
				</view>
				<view class="search-box" @click="goSearch">
					<u-icon name="search" size="16" color="#999"></u-icon>
					<text class="search-text">搜索商品/商家</text>
				</view>
				<view class="nav-right">

					<view class="message-btn" @click="goMessage">
						<u-icon name="bell" size="20" color="#fff"></u-icon>
						<view class="message-dot" v-if="hasNewMessage"></view>
					</view>
				</view>
			</view>
		</view>



		<!-- 搜索栏 -->
		<!-- <view class="search-section">
			<view class="search-box" @click="goSearch">
				<u-icon name="search" size="16" color="#999"></u-icon>
				<text class="search-text">搜索商品</text>
			</view>
		</view> -->

		<!-- 分类内容 -->
		<view class="category-content">
			<!-- 左侧分类列表 -->
			<view class="category-left">
				<scroll-view scroll-y class="category-scroll" :show-scrollbar="false">
					<view class="category-item" v-for="(item, index) in categoryList" :key="index"
						:class="{active: currentCategoryIndex === index}" @click="selectCategory(index)">
						<image :src="item.icon" class="category-icon" v-if="item.icon"></image>
						<text class="category-name">{{ item.name }}</text>
						<view class="category-badge" v-if="item.badge">{{ item.badge }}</view>
					</view>
				</scroll-view>
			</view>

			<!-- 右侧商品列表 -->
			<view class="product-right">
				<scroll-view scroll-y class="product-scroll" :show-scrollbar="false">
					<!-- 子分类 -->
					<view class="sub-category-section" v-if="currentCategoryIndex==0">
						<view class="sub-category-title">
							<text class="title-text">{{ currentCategory.name }}</text>
						</view>
						<view class="sub-category-grid">
							<view class="sub-category-item" v-for="(subItem, subIndex) in currentCategory.children"
								:key="subIndex" @click="goSubCategory(subItem)">
								<image :src="defaults.defaults.baseUrl+subItem.file_path" class="sub-category-image">
								</image>
								<text class="sub-category-name">{{ subItem.name }}</text>
							</view>
						</view>
					</view>

					<!-- 推荐商品 -->
					<view class="recommend-section" v-else>
						<!-- 顶部蓝色区域 -->
						<view class="recommend-banner">
							<image :src="defaults.defaults.baseUrl+banner" class="banner-image"></image>
						</view>

						<!-- 分类商品列表 -->
						<view class="category-products-container">
							<!-- 分类标题和商品列表 -->
							<view class="category-group" v-for="(group, groupIndex) in productList" :key="groupIndex">
								<!-- 分类标题 -->
								<view class="category-title" v-if="group.name">
									<text>{{ group.name }}</text>
								</view>

								<!-- 商品网格 -->
								<view class="product-grid">
									<view class="product-category-item" v-for="(item, index) in group.children"
										:key="index" @click="goSubCategory(item)">
										<image :src="defaults.defaults.baseUrl+item.file_path"
											class="category-product-image"></image>
										<text class="category-product-name">{{ item.name }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
					
					<!-- 底部安全区域 -->
					<view class="bottom-safe-area"></view>
				</scroll-view>
			</view>
		</view>

		<!-- 动态底部导航 -->
		<dynamic-tabbar></dynamic-tabbar>
	</view>
</template>

<script>
	import api from '@/api/index.js'
	import {
		inject
	} from 'vue'
	import DynamicTabbar from '@/components/dynamic-tabbar.vue'

	export default {
		components: {
			DynamicTabbar
		},
		data() {
			return {
				// 小程序适配相关
				statusBarHeight: 0,
				navBarHeight: 44,
				menuButtonInfo: {},
				windowWidth: 375,

				defaults: inject('$defaults'),
				currentCategoryIndex: 0,
				categoryList: [],
				originalCategoryList: [],
				productList: [],
				loading: false,
				loadingProducts: false,
				banner: ''
			}
		},
		computed: {
			currentCategory() {
				return this.categoryList[this.currentCategoryIndex] || {}
			},
			// 处理分类商品数据，按照分类标题分组
			categoryGroups() {
				if (!this.currentCategory.children || this.currentCategory.children.length === 0) {
					return []
				}

				// 按照分类标题分组
				const groups = []
				let currentGroup = null
				let currentTitle = ''

				// 遍历所有子分类
				this.currentCategory.children.forEach(item => {
					// 如果是有机食品，使用特殊样式
					if (item.name && item.name.includes('有机')) {
						if (currentGroup) {
							currentGroup.specialItem = item
						} else {
							// 如果没有当前分组，创建一个新分组
							currentGroup = {
								title: item.name.split('食品')[0] + '食品',
								items: [],
								specialItem: item
							}
							groups.push(currentGroup)
						}
						return
					}

					// 提取分类标题（例如：从"米面杂粮"中提取"米面"作为标题）
					let title = ''
					if (item.name) {
						// 尝试提取前两个字作为分类标题
						title = item.name.substring(0, 2)
					}

					// 如果标题变化，创建新分组
					if (title && title !== currentTitle) {
						currentTitle = title
						currentGroup = {
							title: title,
							items: [item],
							specialItem: null
						}
						groups.push(currentGroup)
					} else if (currentGroup) {
						// 添加到当前分组
						currentGroup.items.push(item)
					} else {
						// 如果没有当前分组，创建一个新分组
						currentGroup = {
							title: title || '推荐',
							items: [item],
							specialItem: null
						}
						groups.push(currentGroup)
					}
				})

				return groups
			}
		},
		onLoad() {
			this.initMiniProgramAdapt()
			this.loadCategoryData()
		},

		// 下拉刷新
		onPullDownRefresh() {
			this.loadCategoryData().finally(() => {
				uni.stopPullDownRefresh()
			})
		},
		methods: {
			// 小程序适配初始化
			initMiniProgramAdapt() {
				// 获取系统信息
				const systemInfo = uni.getSystemInfoSync()
				this.statusBarHeight = systemInfo.statusBarHeight || 0
				this.windowWidth = systemInfo.windowWidth || 375

				// 获取胶囊按钮信息（仅小程序）
				// #ifdef MP
				try {
					this.menuButtonInfo = uni.getMenuButtonBoundingClientRect() || {
						width: 87,
						height: 32,
						top: this.statusBarHeight + 6,
						right: 7,
						bottom: this.statusBarHeight + 38,
						left: this.windowWidth - 94
					}
					this.navBarHeight = this.menuButtonInfo.height + (this.menuButtonInfo.top - this.statusBarHeight) * 2
				} catch (e) {
					console.error('获取胶囊按钮信息失败:', e)
					this.menuButtonInfo = {
						width: 87,
						height: 32,
						top: this.statusBarHeight + 6,
						right: 7,
						bottom: this.statusBarHeight + 38,
						left: this.windowWidth - 94
					}
					this.navBarHeight = 44
				}
				// #endif

				// #ifndef MP
				this.menuButtonInfo = {
					width: 0,
					height: 0,
					top: 0,
					right: 0,
					bottom: 0,
					left: 0
				}
				// #endif
			},
			// 加载分类数据
			async loadCategoryData() {
				if (this.loading) return

				try {
					this.loading = true

					const result = await api.goodsApi.getCategoryList()

					if (result.r === 0) {
						const categories = result.data.fl || []

						// 处理分类数据
						this.categoryList = categories.map(item => ({
							id: item.id,
							name: item.name,
							icon: item.category_icon || '/static/icons/default.png',
							// badge: item.badge_text || '',
							children: result.data.Recommend
						}))
						// this.currentProducts = result.data.Recommend

						// 如果有分类数据，加载第一个分类的商品
						if (this.categoryList.length > 0) {
							this.loadCategoryProducts(this.categoryList[0].id)
						}
					} else {
						// 如果接口失败，使用默认数据
						this.categoryList = this.originalCategoryList
						console.warn('获取分类数据失败，使用默认数据:', result.msg)
					}
				} catch (error) {
					console.error('加载分类数据失败:', error)
					// 使用默认数据
					this.categoryList = this.originalCategoryList
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 加载分类商品
			async loadCategoryProducts(categoryId) {
				if (this.loadingProducts) return

				try {
					this.loadingProducts = true

					const result = await api.goodsApi.getGoodsByCategory({
						cate_id: categoryId,
						page: 1,
						limit: 20
					})

					if (result.r === 0) {
						console.log('======result=====', result.data.fl)
						const products = result.data.fl || []
						console.log('======products=====', products)
						this.banner = result.data.banner
						// 处理商品数据
						this.productList = products.map(item => ({
							id: item.id,
							name: item.name,
							children: item.three
						}))
						console.log('======qqqqqqqq=====', this.productList)
					} else {
						this.productList = []
					}
				} catch (error) {
					console.error('加载分类商品失败:', error)
					this.productList = []
				} finally {
					this.loadingProducts = false
				}
			},

			// 选择分类
			selectCategory(index) {
				this.currentCategoryIndex = index
				const category = this.categoryList[index]
				console.log('====11111111========', index)

				this.loadCategoryProducts(category.id)

			},

			// 扫码
			scanCode() {
				uni.scanCode({
					success: (res) => {
						// TODO: 处理扫码结果
					}
				})
			},

			// 跳转搜索
			goSearch() {
				uni.navigateTo({
					url: '/pages/search/index'
				})
			},

			// 跳转消息
			goMessage() {
				uni.navigateTo({
					url: '/pages/news/list'
				})
			},

			// 跳转子分类
			goSubCategory(subItem) {
				console.log('=========', subItem)
				uni.navigateTo({
					url: `/pages/product/list?id=${subItem.id}&level=${3}`
				})
			},

			// 跳转商品详情
			goProductDetail(product) {
				uni.navigateTo({
					url: `/pages/goods/detail?id=${product.id}`
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.custom-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		background: linear-gradient(135deg, #FF8033 0%, #FF6B35 100%);

		.navbar-content {
			display: flex;
			align-items: center;
			padding: 0 30rpx;

			.location-btn {
				display: flex;
				align-items: center;
				padding: 10rpx 20rpx;
				border-radius: 30rpx;
				background: rgba(255, 255, 255, 0.2);
				margin-right: 20rpx;
			}

			.location-text {
				margin: 0 10rpx;
				color: #fff;
				font-size: 26rpx;
				max-width: 120rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.search-box {
				flex: 1;
				height: 56rpx;
				background-color: rgba(255, 255, 255, 0.9);
				border-radius: 28rpx;
				display: flex;
				align-items: center;
				padding: 0 24rpx;

				.search-text {
					color: #999;
					font-size: 26rpx;
					margin-left: 12rpx;
				}
			}

			.nav-right {
				display: flex;
				align-items: center;
				margin-left: 20rpx;
			}

			.scan-btn {
				width: 64rpx;
				height: 64rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-right: 16rpx;
			}

			.message-btn {
				width: 64rpx;
				height: 64rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;

				.message-dot {
					position: absolute;
					top: 12rpx;
					right: 12rpx;
					width: 16rpx;
					height: 16rpx;
					background-color: #ff4757;
					border-radius: 50%;
				}
			}
		}
	}

	.classification-container {
		background-color: #f5f5f5;
		padding-top: calc(var(--status-bar-height, 0px) + 88rpx);
		height: 100vh;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
	}

	.search-section {
		background-color: #fff;
		padding: 20rpx 30rpx;
		border-bottom: 2rpx solid #eee;

		.search-box {
			height: 72rpx;
			background-color: #f5f5f5;
			border-radius: 36rpx;
			display: flex;
			align-items: center;
			padding: 0 30rpx;

			.search-text {
				color: #999;
				font-size: 28rpx;
				margin-left: 16rpx;
			}
		}
	}

	.category-content {
		flex: 1;
		display: flex;
		overflow: hidden;
		margin-top: 42rpx;
		margin-bottom: calc(100rpx + env(safe-area-inset-bottom));
	}

	.category-left {
		width: 200rpx;
		background-color: #f8f9fa;
		border-right: 2rpx solid #eee;

		.category-scroll {
			height: 100%;

			.category-item {
				height: 120rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 16rpx;
				position: relative;
				border-bottom: 2rpx solid #eee;

				&.active {
					background-color: #fff;
					border-right: 4rpx solid #FF6B35;

					.category-name {
						color: #FF6B35;
						font-weight: 500;
					}
				}

				.category-icon {
					width: 40rpx;
					height: 40rpx;
					margin-bottom: 8rpx;
				}

				.category-name {
					font-size: 24rpx;
					color: #333;
					text-align: center;
					line-height: 1.2;
				}

				.category-badge {
					position: absolute;
					top: 10rpx;
					right: 10rpx;
					background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
					color: #fff;
					font-size: 16rpx;
					padding: 2rpx 8rpx;
					border-radius: 12rpx;
					transform: scale(0.8);
				}
			}
		}
	}

	.product-right {
		flex: 1;
		background-color: #fff;

		.product-scroll {
			height: 100%;
		}
	}

	.sub-category-section {
		padding: 30rpx;
		border-bottom: 16rpx solid #f5f5f5;

		.sub-category-title {
			margin-bottom: 30rpx;

			.title-text {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
			}
		}

		.sub-category-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 30rpx;

			.sub-category-item {
				display: flex;
				flex-direction: column;
				align-items: center;

				.sub-category-image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 16rpx;
					margin-bottom: 16rpx;
					object-fit: cover;
				}

				.sub-category-name {
					font-size: 24rpx;
					color: #333;
					text-align: center;
				}
			}
		}
	}

	.recommend-section {
		padding: 0;

		// 顶部蓝色区域样式
		.recommend-banner {
			padding: 20rpx 30rpx 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-radius: 0;

			.banner-image {
				width: 100%;
				height: 180rpx;
				object-fit: contain;
			}
		}

		// 分类商品容器
		.category-products-container {
			padding: 0;
			background-color: #fff;

			// 分类组
			.category-group {
				margin-bottom: 15rpx;

				// 分类标题
				.category-title {
					padding: 30rpx 30rpx 20rpx;
					font-size: 32rpx;
					font-weight: 500;
					color: #333;
				}

				// 商品网格
				.product-grid {
					display: grid;
					grid-template-columns: repeat(3, 1fr);
					padding: 0 30rpx;

					// 有机食品特殊项占据整行
					.product-category-item.organic {
						grid-column: span 1;
						background-color: #4cd964;
						border-radius: 10rpx;
						padding: 20rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						margin-bottom: 30rpx;

						.organic-icon {
							width: 80rpx;
							height: 80rpx;
							background-color: rgba(255, 255, 255, 0.2);
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
							margin-bottom: 10rpx;
						}

						.category-product-name {
							color: #fff;
							font-size: 24rpx;
						}
					}

					// 普通商品项
					.product-category-item {
						display: flex;
						flex-direction: column;
						align-items: center;
						padding: 20rpx;

						.category-product-image {
							width: 120rpx;
							height: 120rpx;
							object-fit: contain;
							margin-bottom: 16rpx;
						}

						.category-product-name {
							font-size: 24rpx;
							color: #333;
							text-align: center;
						}
					}
				}
			}
		}
	}

	.bottom-safe-area {
		height: 40rpx;
		background-color: transparent;
	}
</style>